# -*- coding: utf-8 -*-
# auth: lipengcheng

import re
import subprocess
import sys
import threading
from datetime import datetime
from PyQt5 import QtWidgets, QtGui, QtCore, Qt
from PyQt5.QtGui import QTextOption
import time

executeCommandList = []
defaultCommandList = []
packageNameCommandList = []
packageCommandList = []
customCommandList = []
permissionCommandList = []


class GUI(QtWidgets.QWidget):
    # 黑字蓝底
    style_btn_black = "background-color: rgb(164, 185, 255);"
    "border-color: rgb(170, 150, 163);"
    "font: 75 12pt \"Arial Narrow\";"
    "color: rgb(0, 0, 0);"

    style_btn_red = "background-color: rgb(164, 185, 255);"
    "border-color: rgb(170, 150, 163);"
    "font: 75 12pt \"Arial Narrow\";"
    "color: rgb(255, 0, 0);"

    style_red_line = "background-color: rgb(255, 0, 0);"
    "border-color: rgb(170, 150, 163);"
    "font: 75 12pt \"Arial Narrow\";"
    "color: rgb(255, 0, 0);"

    style_black_font = "border-color: rgb(170, 150, 163);"

    xLocations = (10, 620, 860, 1080)
    yLocations = (10, 650)

    screenSize = (1300, 800)
    showContentTeLocation = (xLocations[0], yLocations[0], 600, 630)
    contentLeSize = (400, 20)
    executeBtnSize = (100, 20)
    packageRadioBtnSize = (240, 20)
    btnGapX = 10
    btnGapY = 10

    yFirstColumn = yLocations[1]
    xFirstColumn = xLocations[0] + contentLeSize[0] + btnGapX
    ySecondColumn = yLocations[0]
    yThirdColumn = yLocations[0]
    yFourthColumn = yLocations[0]

    countCmd = 0
    mPackage = None
    countSystemBtn = 0

    def __init__(self):
        super().__init__()
        self.initGUI()

    def initGUI(self):
        # 窗体
        self.resize(self.screenSize[0], self.screenSize[1])
        qr = self.frameGeometry()
        cp = QtWidgets.QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
        self.setWindowTitle('adb-tool')
        # self.setWindowIcon(QtGui.QIcon('adb-tool.png'))

        # 输出内容
        self.showContentTE = QtWidgets.QTextEdit(self)
        self.showContentTE.setGeometry(QtCore.QRect(self.showContentTeLocation[0], self.showContentTeLocation[1],
                                                    self.showContentTeLocation[2], self.showContentTeLocation[3]))
        self.showContentTE.setStyleSheet(self.style_black_font)
        self.showContentTE.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop)
        self.showContentTE.setWordWrapMode(QTextOption.NoWrap)

        # 输入框
        self.contentLE = Qt.QLineEdit(self)
        self.contentLE.resize(self.contentLeSize[0], self.contentLeSize[1])
        self.contentLE.move(self.xLocations[0], self.yLocations[1])
        self.contentLE.setPlaceholderText("指令")

        # 执行相关按钮
        self.addExecuteBtns()

        # pull/push
        self.yFirstColumn = self.yFirstColumn + self.executeBtnSize[1] + self.btnGapY
        print("self.yFirstColumn222 = " + str(self.yFirstColumn))
        self.textboxDevice = self.addLineEdit("手机资源路径", self.xLocations[0], self.yFirstColumn)
        self.textboxMac = self.addLineEdit("电脑资源路径", self.xLocations[0] + 280 + self.btnGapX, self.yFirstColumn)
        self.addBtn(self.xLocations[0] + 280 + self.btnGapX + 280 + self.btnGapX, self.yFirstColumn,
                    "pull", "").clicked.connect(lambda: self.pullfile(self.textboxDevice, self.textboxMac))
        self.addBtn(self.xLocations[0] + 280 + self.btnGapX + 280 + self.btnGapX + 100 + self.btnGapX,
                    self.yFirstColumn, "push", "").clicked.connect(lambda: self.pushfile(self.textboxDevice, self.textboxMac))
        # pull/push
        self.yFirstColumn = self.yFirstColumn + self.executeBtnSize[1] + self.btnGapY
        print("self.yFirstColumn333 = " + str(self.yFirstColumn))
        self.textboxDevice2 = self.addLineEdit("手机资源路径", self.xLocations[0], self.yFirstColumn)
        self.textboxMac2 = self.addLineEdit("电脑资源路径", self.xLocations[0] + 280 + self.btnGapX, self.yFirstColumn)
        self.addBtn(self.xLocations[0] + 280 + self.btnGapX + 280 + self.btnGapX, self.yFirstColumn,
                    "pull", "").clicked.connect(lambda: self.pullfile(self.textboxDevice2, self.textboxMac2))
        self.addBtn(self.xLocations[0] + 280 + self.btnGapX + 280 + self.btnGapX + 100 + self.btnGapX,
                    self.yFirstColumn, "push", "").clicked.connect(lambda: self.pushfile(self.textboxDevice2, self.textboxMac2))

        # 系统按钮
        self.addSystemBtns()

        # 默认按钮
        self.addDefaltBtns()

        self.addLine(self.xLocations[2] - 10, 0, 1, self.screenSize[1])

        # 包名按钮
        for index, pair in enumerate(packageNameCommandList):
            if index == 0:
                self.defaultRb = self.addRadioBtn(pair.value)
            elif index == len(packageNameCommandList) - 1:
                self.lastRb = self.addRadioBtn(pair.value)
            else:
                self.addRadioBtn(pair.value)
        # 包名相关操作按钮
        self.addPackageBtns()
        self.defaultRb.toggle()

        self.addLine(self.xLocations[3] - 10, 0, 1, self.screenSize[1])

        # 自定义按钮
        self.addCustomBtns()

        self.show()

    def grantPermission(self):
        for pair in permissionCommandList:
            self.clickBtn("adb shell pm grant %s %s;"
                          % (self.mPackage, pair.value))

    def pullfile(self, btn_device, btn_mac):
        self.clickBtn("adb pull %s %s" % (btn_device.text(), btn_mac.text()))

    def pushfile(self, btn_device, btn_mac):
        self.clickBtn("adb push %s %s" % (btn_mac.text(), btn_device.text()))

    def addPackageName(self):
        self.lastRb.setText(self.contentLE.text())
        self.btn_state(self.lastRb)

    def startLogcat(self):
        print("开启LogcatThread....")
        self.clickBtn("")
        # logThread = threading.Thread(target=self.logcatThread2())
        # logThread.start()
        thrad = self.LogcatThread()
        thrad.start()
        print("开启LogcatThread完毕....")

    def stopLogcat(self):
        self.clickBtn("adb shell killall -2 logcat")

    def openLogDir(self):
        self.clickBtn("open ~/Desktop/")

    def clear(self):
        self.showContentTE.setPlainText("")
        self.countCmd = 0

    def btn_state(self, btn):
        if btn.isChecked():
            self.mPackage = btn.text()
            self.updateTextEdit("设置默认包名为：" + self.mPackage)

    def clickBtn(self, cmd, placeType=0):
        self.countCmd = self.countCmd + 1
        self.updateTextEdit("-----------------------" + str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))) + "---------------------------")
        if placeType == 1:
            releaseCmd = cmd % (self.mPackage)
        elif placeType == 2:
            releaseCmd = cmd % (self.contentLE.text())
        else:
            releaseCmd = cmd
        self.updateTextEdit("指令：" + releaseCmd)
        self.updateTextEdit("结果：------")
        self.exeCmd(releaseCmd)

    def updateTextEdit(self, content):
        if self.showContentTE.toPlainText() == "":
            self.showContentTE.setPlainText(content)
        else:
            self.showContentTE.setPlainText(self.showContentTE.toPlainText() + "\r\n" + content)
        self.showContentTE.moveCursor(self.showContentTE.textCursor().End)

    def exeCmd(self, cmd):
        if cmd == "":
            return
        else:
            print("cmd = " + cmd)
        try:
            process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            while process.poll() is None:
                result = process.stdout
                content = result.readline().decode('utf-8')
                while content:
                    self.updateTextEdit(content)
                    content = result.readline().decode('utf-8')

                errResult = process.stderr
                errContent = errResult.readline().decode('utf-8')
                while errContent:
                    self.updateTextEdit(errContent)
                    errContent = errResult.readline().decode('utf-8')
            self.updateTextEdit("")
        except Exception as e:
            self.updateTextEdit("e.args" + e.args)
        finally:
            result.close()
            errResult.close()

    def keyPressEvent(self, event):
        # 这里event.key（）显示的是按键的编码
        if (str(event.key()) == "16777220" or str(event.key()) == "16777221"):
            self.clickBtn(self.contentLE.text())

    def addExecuteBtns(self):
        self.addExecuteBtn("执行", "%s")
        self.addExecuteBtn("Package Name", "").clicked.connect(lambda: self.addPackageName())

        for index, pair in enumerate(executeCommandList):
            if index < 9:
                self.addExecuteBtn(pair.name, pair.value)

    def addExecuteBtn(self, name, value):
        if self.xFirstColumn > (self.xLocations[2] - self.btnGapX - self.executeBtnSize[0]):
            self.xFirstColumn = self.btnGapX
            self.yFirstColumn = self.yFirstColumn + self.executeBtnSize[1] + self.btnGapY
        btn = self.addBtn(self.xFirstColumn, self.yFirstColumn, name, value, 2)
        self.xFirstColumn = self.xFirstColumn + self.executeBtnSize[0] + self.btnGapX
        return btn

    def addCustomBtns(self):
        for index, pair in enumerate(customCommandList):
            if index >= 1:
                self.yFourthColumn = self.yFourthColumn + self.executeBtnSize[1] + self.btnGapY
            btn = self.addBtn(self.xLocations[3], self.yFourthColumn, pair.name, pair.value)
            btn.resize(200, self.executeBtnSize[1])

    def addPackageBtns(self):
        self.addBtn(self.xLocations[2], self.yThirdColumn, "应用授权", "", 1).clicked.connect(lambda: self.grantPermission())
        for index, pair in enumerate(packageCommandList):
            self.yThirdColumn = self.yThirdColumn + self.executeBtnSize[1] + self.btnGapY
            self.addBtn(self.xLocations[2], self.yThirdColumn, pair.name, pair.value, 1)

    def addSystemBtns(self):
        self.addSystemBtn("清屏").clicked.connect(lambda: self.clear())
        self.addSystemBtn("log目录").clicked.connect(lambda: self.openLogDir())
        self.addSystemBtn("log").clicked.connect(lambda: self.startLogcat())
        self.addSystemBtn("停止log").clicked.connect(lambda: self.stopLogcat())

        self.ySecondColumn = self.ySecondColumn + self.executeBtnSize[1] + self.btnGapY

    def addSystemBtn(self, text):
        if self.countSystemBtn % 2 == 0:
            x = 0
        else:
            x = self.executeBtnSize[0] + self.btnGapX
        if self.countSystemBtn > 0 and (self.countSystemBtn % 2) == 0:
            self.ySecondColumn = self.ySecondColumn + self.executeBtnSize[1] + self.btnGapY
        self.countSystemBtn = self.countSystemBtn + 1
        return self.addBtn(self.xLocations[1] + x, self.ySecondColumn, text, "")

    def addDefaltBtns(self):
        for index, pair in enumerate(defaultCommandList):
            if index % 2 == 0:
                x = 0
            else:
                x = self.executeBtnSize[0] + self.btnGapX
            if index > 0 and (index % 2) == 0:
                self.ySecondColumn = self.ySecondColumn + self.executeBtnSize[1] + self.btnGapY
            self.addBtn(self.xLocations[1] + x, self.ySecondColumn, pair.name, pair.value)

    def addBtn(self, xLocation, yLocation, name, cmd, placeType=0):
        btn = QtWidgets.QPushButton('按钮', self)
        btn.resize(self.executeBtnSize[0], self.executeBtnSize[1])
        btn.move(xLocation, yLocation)
        btn.setText(name)
        btn.setStyleSheet(self.style_btn_black)
        if cmd != "":
            btn.clicked.connect(lambda: self.clickBtn(cmd, placeType))
        return btn

    def addRadioBtn(self, text):
        radioButton = Qt.QRadioButton(self)
        radioButton.resize(self.packageRadioBtnSize[0], self.packageRadioBtnSize[1])
        radioButton.move(self.xLocations[2], self.yThirdColumn)
        radioButton.setText(text)
        radioButton.toggled.connect(lambda: self.btn_state(radioButton))
        radioButton.setStyleSheet("color: rgb(255, 255, 255);")

        self.yThirdColumn = self.yThirdColumn + 30
        return radioButton

    def addLineEdit(self, text, xLocation, yLocation):
        lineEdit = Qt.QLineEdit(self)
        lineEdit.resize(280, 20)
        lineEdit.move(xLocation, yLocation)
        lineEdit.setPlaceholderText(text)
        return lineEdit

    def addLine(self, x, y, width, height):
        self.line = QtWidgets.QLabel(self)
        self.line.resize(width, height)
        self.line.move(x, y)
        self.line.setText('')
        self.line.setStyleSheet(self.style_red_line)

    class LogcatThread(threading.Thread):

        def __init__(self):
            super().__init__()

        def run(self):
            gui.exeCmd(
                "adb logcat -c && adb logcat > ~/Desktop/log-%s.txt" % (datetime.now().strftime('%Y-%m-%d-%H_%M_%S')))
            print("LogcatThread退出...")


class pair:
    def __init__(self, name, value):
        self.name = name
        self.value = value


def readCommandsFile(path):
    path = path + "commands.txt"
    print(path)
    fileDefault = "###default###"
    filePackageName = "###packageName###"
    filePackage = "###package###"
    fileCustom = "###custom###"
    fileExecute = "###execute###"
    filePermission = "###permission###"
    currentCommandList = None
    with open(path, 'rb') as file:
        while True:
            # 按行读取
            line = str(file.readline().decode('utf-8', errors='ignore')).strip()
            if line:
                # 多虑
                if re.search(fileDefault, line):
                    currentCommandList = defaultCommandList
                elif re.search(filePackageName, line):
                    currentCommandList = packageNameCommandList
                elif re.search(filePackage, line):
                    currentCommandList = packageCommandList
                elif re.search(fileCustom, line):
                    currentCommandList = customCommandList
                elif re.search(fileExecute, line):
                    currentCommandList = executeCommandList
                elif re.search(filePermission, line):
                    currentCommandList = permissionCommandList
                elif re.search("###", line):
                    index = line.index("###")
                    currentCommandList.append(pair(line[0:index], line[index + 3:len(line)]))
                else:
                    pass
            else:
                break


if __name__ == '__main__':
    pythonPath = sys.argv[0][0:sys.argv[0].rfind("/") + 1]
    readCommandsFile(pythonPath)
    app = QtWidgets.QApplication(sys.argv)
    global gui
    gui = GUI()
    sys.exit(app.exec_())
